//
//  TSTableViewCardCollectionViewController.swift
//  TSListDemo
//
//  Created by qian on 2020/11/6.
//  Copyright © 2020 dvlproad. All rights reserved.
//

import UIKit
import SnapKit
import CJBaseUIKit
import MJExtension
import CQDemoKit
import CQUserDetailModel

let maxLikeCount: NSInteger = 5

class TSTableViewCardCollectionViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
    var collectionView: CQTableViewCardCollectionView?
    fileprivate let identifier = "CQTableViewCardCollectionViewCell"
    var collectionViewCellWidth: CGFloat = 0    // 匹配成功卡片的弹出需要使用
    var collectionViewCellHeight: CGFloat = 0   // 卡片正常展示的时候就需要使用
    
    var barButtonView: CardBarButtonItemView?
    
    // MARK: - Setter
    // 今日喜欢次数
    private var _todayLikeCount :NSInteger!
    var todayLikeCount: NSInteger {
        set {
            self._todayLikeCount = newValue
            let remainingLikeCount: NSInteger = maxLikeCount - newValue
            self.barButtonView?.barItemLabel?.text = String.init(format: "%zd", remainingLikeCount)
        }
        get {
            return self._todayLikeCount
        }
    }
    
    // MARK: - LifeStyle
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        requestData(false)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupViews()
        
        self.todayLikeCount = 2
    }
    
    // MARK: - Event
    @objc func goMenu() {
        // TODO:进入Menu,待完善
        debugPrint("进入Menu,待完善")
    }
    
    // MARK: - SetupViews
    private func setupViews() {
        self.navigationItem.title = NSLocalizedString("发现", comment: "发现")
        
        self.setupBarButtonItem()
        
        self.setupCardView();
    }
    
    /// 设置导航栏上的按钮
    private func setupBarButtonItem() {
        // 左按钮
        let menuImage: UIImage = UIImage.init(named: "icon_like")!
        let menuBarButtonItem: UIBarButtonItem = UIBarButtonItem.init(image: menuImage, style: UIBarButtonItem.Style.plain, target: self, action: #selector(goMenu))
        self.navigationItem.leftBarButtonItems = [menuBarButtonItem]
        
        // 右按钮
        let barButtonView: CardBarButtonItemView = CardBarButtonItemView.init(frame: CGRect.init(x: 0, y: 0, width: 44, height: 44), clickAction: {
            let message: String = String.init(format: "您还剩余%zd个匹配喔", self.todayLikeCount)
            debugPrint("\(message)")
        })
        self.barButtonView = barButtonView
        let rightBarButtonItem: UIBarButtonItem = UIBarButtonItem.init(customView: barButtonView)
        self.navigationItem.rightBarButtonItems = [rightBarButtonItem]
    }
    
    
    /// 设置卡片视图
    private func setupCardView() {
        let leftPadding: CGFloat = 10
        let topPadding: CGFloat = 30
        let collectionViewFlowLayout = CQTTCardCollectionViewFlowLayout.init(leftRightPadding: leftPadding, topPadding: topPadding, bottomPadding: topPadding)
        collectionView = CQTableViewCardCollectionView(frame: CGRect.zero, collectionViewLayout: collectionViewFlowLayout)
        collectionView?.scrollsToTop = false
        
        collectionView?.register(CQTableViewCardCollectionViewCell.self, forCellWithReuseIdentifier: identifier)
        collectionView?.dataSource = self
        collectionView?.delegate = self
        self.view.addSubview(collectionView!)
        collectionView?.snp_makeConstraints({ (make) in
            make.centerX.equalTo(self.view)
            make.left.equalTo(self.view).offset(0)
            make.top.equalTo(self.view.snp_topMargin).offset(0)
            make.bottom.equalTo(self.view.snp_bottomMargin).offset(-0)
        })
        
        // 计算 collectionView 的 Height 和 collectionViewCellHeight
        let screenHeight = UIScreen.main.bounds.size.height
        let statusBarHeight = UIApplication.shared.statusBarFrame.size.height
        let navigationBarHeight = self.navigationController?.navigationBar.frame.size.height ?? 0
        let tabbarHeight = self.tabBarController?.tabBar.frame.height ?? 0
        let screenWidth = UIScreen.main.bounds.size.width
        let iphoneX = screenWidth >= 375.0 && screenHeight >= 812.0
        let bottomGuideHeight: CGFloat = iphoneX ? 34 : 0
        let collectionViewHeight = screenHeight - statusBarHeight - navigationBarHeight - tabbarHeight - bottomGuideHeight
        let collectionViewCellHeight = collectionViewHeight - 2*topPadding;
        self.collectionViewCellHeight = collectionViewCellHeight
        
        let collectionViewWidth = screenWidth - 2*leftPadding
        self.collectionViewCellWidth = collectionViewWidth
        
        
        
        collectionView?.layoutIfNeeded()
        
        
        collectionView?.addPanGest()
        
        
        collectionView?.panChangeBlock = { (bIsLeft: Bool, bCell, percentValue) -> (Void) in
            let cell = bCell as! CQTableViewCardCollectionViewCell
            
            if bIsLeft {
                cell.hateView.alpha = percentValue
                cell.likeView.alpha = 0
            } else {
                cell.hateView.alpha = 0
                cell.likeView.alpha = percentValue
            }
        }
        
        collectionView?.checkRemoveEnableBlock = { (moveState: CQCardMoveState) -> (Bool) in
            var removeEnable: Bool = true
            
            switch moveState {
                case .MoveInside:
                    removeEnable = false
                    break
                case .MoveTooFastRight, .MoveOutRight:
                    removeEnable = self.todayLikeCount < maxLikeCount
                    break
                default:
                    removeEnable = true
                    break
                }
            return removeEnable
        }
        collectionView?.panCompleteBlock = { (likeType: CQCardLikeType, bCell: CQBaseCardCollectionViewCell) -> (Void) in
            let canLike: Bool = self.todayLikeCount < maxLikeCount
            switch likeType {
                case .None:
                    let cell: CQTableViewCardCollectionViewCell = bCell as! CQTableViewCardCollectionViewCell
                    cell.hateView.alpha = 0
                    cell.likeView.alpha = 0
                    if canLike == false {
                        // 显示广告等其他操作
                    }
                    break
                case .Like, .SuperLike:
                    self.requestLikeType(likeType: likeType) { (isSuccess: Bool) -> (Void) in
                        if isSuccess {
                            self.todayLikeCount += 1
                        }
                    }
                    break
                case .Hate, .SuperHate:
                    self.requestLikeType(likeType: likeType) { (isSuccess: Bool) -> (Void) in
                        debugPrint("不喜欢，不做次数累计")
                    }
                    break
                }
            
            let isLastCard: Bool = self.collectionView!.showDataSource.count == 1
            if isLastCard {
                self.requestData(true)
            }
        }
    }
    
    
    // MARK: - Request
    fileprivate func requestData(_ refreshNext: Bool) {
        CJRequestSimulateUtil.localSimulateApi("api/card/cardlist") { (responseDictionary) in
            debugPrint("responseDictionary = \(responseDictionary)")
            let dictionarys = responseDictionary["result"]
            
            
            let array = CQUserDetailModel.mj_objectArray(withKeyValuesArray: dictionarys) as! Array<CQUserDetailModel>
            self.collectionView?.addUserDetailModels(array: array)
        }
    }
    
    fileprivate func requestLikeType(likeType: CQCardLikeType, success:((_ isSuccess: Bool)->(Void))?) {
        
        CJRequestSimulateUtil.localSimulateApi("api/card/readover") { (responseDictionary) in
            debugPrint("responseDictionary = \(responseDictionary)")
            let dictionary: NSDictionary = responseDictionary["result"] as! NSDictionary
            
            let readResultModel: CQCardReadResultModel = CQCardReadResultModel.mj_object(withKeyValues: dictionary)
            
            
//            let likeTypeValue = readResultModel.likeType
//            let newLikeType: CQCardLikeType = CQCardLikeType(rawValue: likeTypeValue ) ?? .None
//            switch newLikeType {
//            case .Like:
            
            if (likeType == CQCardLikeType.Like || likeType == CQCardLikeType.SuperLike) {
                (success ?? { (isSuccess: Bool) -> (Void) in })(true)
                
                if readResultModel.matchModels.count > 0 { // 检测到匹配对象，弹出匹配成功窗口
                    let matchUser: CQUserMatchModel = readResultModel.matchModels[0]
                    
                    let popupViewWidth: CGFloat = self.collectionViewCellWidth
                    let popupViewHeight: CGFloat = self.collectionViewCellHeight
                    let cardMatchView: CQCardMatchView = CQCardMatchView.init(frame: CGRect.init(x: 0, y: 0, width: popupViewWidth, height: popupViewHeight))
                    cardMatchView.matchUser = matchUser
                    cardMatchView.continueBlock = { () -> () in
//                        cardMatchView.cqPopup_center_hide()
                        CJUIKitAlertUtil.showIKnowAlert(in: self, withTitle: "继续探索") {
                        }
                    }
                    cardMatchView.chatBlock = { () -> () in
//                        cardMatchView.cqPopup_center_hide()
                        CJUIKitAlertUtil.showIKnowAlert(in: self, withTitle: "开始聊天") {
                        }
                    }
                    
                    
//                    cardMatchView.cqPopup_center_show(with: CGSize.init(width: popupViewWidth, height: popupViewHeight), centerOffset: CGPoint.init(x: 0, y: 30))
                }
            }
//                break
//            case .None:
//                // 喜欢失败，进行返回
//                break
//            default:
//                break
//            }
        }
    }
    
    
    // MARK: - UICollectionViewDataSource
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.collectionView!.showDataSource.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as! CQTableViewCardCollectionViewCell
        cell.indexPathItem = indexPath.row
        cell.likeView.alpha = 0
        cell.hateView.alpha = 0
        cell.tableView.contentOffset = CGPoint.zero
        cell.tableView.tableHeaderViewHeight = self.collectionViewCellHeight
        
        let cardInfoModel: CQUserDetailModel = self.collectionView!.showDataSource[indexPath.row] as! CQUserDetailModel
        cell.tableView.infoModel = cardInfoModel
        return cell
    }
}
